<template>
  <el-table
      v-loading="isLoading"
      :cell-style="cellStyle"
      :data="shops"
      :tree-props="tableTreeProps"
      border
      default-expand-all
      highlight-current-row
      row-key="selfid"
      size="large"
      @current-change="handleCurrentChange"
  >
    <el-table-column label="门店" prop="shop_name"/>
  </el-table>
</template>
<script lang="ts" setup>
import {ProcessedShopResponse, ShopResponse} from "@/api/types/shop";
import {getShops} from "@/api/shop";
import {ref} from "vue";

const shops = ref<ShopResponse[]>([])
const emit = defineEmits<{
  currentChange: [shopId: number, shopName: string]
}>()
const isLoading = ref(false)
const tableTreeProps = {
  children: "childs"
}
const cellStyle = {
  fontWeight: "bold",
  cursor: "pointer"
}

async function getData() {
  if (isLoading.value === false) {
    isLoading.value = true
  }
  const {result} = await getShops()
  if (result !== undefined) {
    shops.value = [{
      level: 1,
      shop_name: import.meta.env.VITE_SHOP_NAME,
      childs: result.map(shopResponse => ({
        ...shopResponse,
        level: 2,
        childs: shopResponse.childs?.map(shopResponse => ({
          ...shopResponse,
          level: 3,
        } as ProcessedShopResponse))
      })),
      selfid: 0,
    } as ProcessedShopResponse]
    isLoading.value = false
  }
}

getData()

function handleCurrentChange({selfid, shop_name, isarea}: ShopResponse) {
  if (selfid !== undefined && shop_name !== undefined) {
    emit("currentChange", selfid, shop_name, isarea)
  }
}
</script>
